import React, { useEffect, useState, useCallback } from 'react';
import { connect } from 'dva';
import { Table, Button, Popconfirm, message } from 'antd';
import { PlusOutlined, DownloadOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import TableSelector from './components/TableSelector';
import AddForm from './components/AddForm';
import style from '@/pages/IndexPage.css';

function MachArchives({ dispatch, user, mach }){
    const { authorized } = user;
    const { machList, machTypes, currentPage, total } = mach;
    const [info, setInfo] = useState({});
    useEffect(()=>{
        if ( authorized ) {
            dispatch({ type:'mach/fetchMachList' });
        }
    },[authorized])
    const columns = [
        { title:'设备名称', dataIndex:'meterName' },
        { title:'设备类型', dataIndex:'energyType', render:value=>{
            let obj = machTypes.filter(i=>i.typeCode == value )[0];
            console.log(machTypes);
            console.log(obj);
            return (<span>{ obj ? obj.typeName : '--' }</span>)
        }},
        { title:'注册码', dataIndex:'registerCode' },
        { title:'功率', dataIndex:'ratedPower', render:value=> value ? value + 'kw' : '--' },
        // { title:'品牌', dataIndex:'brand' },
        { title:'型号', dataIndex:'model', render:value=>value || '--' },
        { title:'安装位置', dataIndex:'pos', render:value=>value || '--' },
        // { title:'设备厂商', dataIndex:'com' },
        { title:'创建日期', dataIndex:'createTime' },
        // { title:'设备状态', dataIndex:'status' },
        {
            title:'操作',
            render:row=>(
                <div>
                    <Button type='link' size='small' icon={<EditOutlined />} onClick={()=>setInfo({ visible:true, current:row, forEdit:true })}>更新</Button>
                    <Popconfirm cancelText='取消' okText='确定' title={`确认删除${row.meterName}`} onConfirm={()=>{
                        new Promise((resolve, reject)=>{
                            dispatch({ type:'mach/delMachAsync', payload:{ resolve, reject, machId:row.machId }})
                        })
                        .then(()=>{
                            message.success(`删除${row.meterName}成功`);
                        })
                        .catch(msg=>{
                            message.error(msg);
                        })
                    }}>
                        <Button type='text' size='small' danger icon={<DeleteOutlined />}>删除</Button>
                    </Popconfirm>
                </div>
            )
        }
    ];
    const handleDispatch = useCallback((action) => {
        dispatch(action);
    }, []);
    const handleSearch = useCallback((obj) => {
        dispatch({ type: 'mach/setOptional', payload:obj });
        dispatch({ type: 'mach/fetchMachList' });
    }, []);
    
    return (
        <div className={style['page-container']}>
            <div style={{ height:'90px' }}>
                <TableSelector modelTypes={machTypes} onSearch={handleSearch} />
            </div>
            <div style={{ height:'calc( 100% - 90px)', paddingTop:'1rem' }}>
                <div className={style['card-container']} style={{ paddingTop:'1rem' }}>
                    <div className={style['card-title']}>
                        <div>
                            <Button type='primary' style={{ marginRight:'1rem' }} icon={<PlusOutlined />} onClick={()=>setInfo({ visible:true })}>新建</Button>
                            <Button>批量导入</Button>
                        </div>
                        <Button icon={<DownloadOutlined />}>下载</Button>
                    </div>
                    <div className={style['card-content']}>
                        <Table
                            className={style['self-table-container']}
                            style={{ padding:'0' }}
                            columns={columns}
                            dataSource={machList}
                            rowKey="machId"
                            pagination={{
                                current: currentPage,
                                total,
                                pageSize: 12,
                                showSizeChanger: false,
                            }}
                            onChange={(pagination) => {
                                dispatch({
                                  type: 'mach/fetchMachList',
                                  payload: { currentPage: pagination.current },
                                });
                            }}
                        />
                    </div>
                </div>
                {/* 添加设备档案 */}             
                <AddForm
                    info={info}
                    onDispatch={handleDispatch}
                    onClose={() => setInfo({})}                       
                    machTypes={machTypes}
                />
            </div>
        </div>
    )
}

export default connect(({ user, mach })=>({ user, mach }))(MachArchives)